<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page isELIgnored="true" %>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>考试</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
    <style>
        .el-header {
            min-height: 64px;
            color: #fff;
            background-color: #009688;
        }

        .well {
            min-height: 20px;
            padding: 19px;
            /*margin-bottom: 20px;*/
            background-color: #f5f5f5;
            border: 1px solid #e3e3e3;
            border-radius: 4px;
            -webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 5%);
            box-shadow: inset 0 1px 1px rgb(0 0 0 / 5%);
        }

        .mainContainer {
            max-width: 1300px;
            margin: 0 auto;
            padding: 16px;
        }

        .mainContainerRight {
            width: 880px;
        }

        .MyBorder {
            border: 1px solid #e8e8e8;
            border-radius: 4px;
        }

        .simple-answer-card {
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 1px 6px rgb(0 0 0 / 12%), 0 1px 4px rgb(0 0 0 / 12%);
        }

        .myQuestionItm {
            background: #fff;
        }

        .myQuestionItm_finish {
            background: #2ecc71;
            color: #fff;
        }

        .answerSheet {
            min-width: 200px;
        }

        .exam-box {
            padding: 16px;
            margin-bottom: 24px;
            box-shadow: 0 1px 6px rgb(0 0 0 / 12%), 0 1px 4px rgb(0 0 0 / 12%);
        }


    </style>
</head>
<body>
<div id="answerQuestionsApp">
    <el-container>
        <el-header class="flex justify-between content-center items-center">
            <div class="text-3xl leftTitle">欢迎使用考试系统</div>
            <div class="text-lg">{{paperName}}</div>
            <div>
                <el-button>放弃作答<i class="el-icon-circle-close el-icon--right"></i></el-button>
                <el-button type="success" icon="el-icon-upload" @click="carryOutAnAssignment">交卷</el-button>
            </div>
        </el-header>

        <el-main>
            <div class="mainContainer flex">
                <div class="simple-answer-card answerSheet flex-grow">
                    <div class="font-bold text-xl">答题卡</div>
                    <el-divider></el-divider>
                    <div class="mt-2 flex flex-wrap">
                        <div class="rounded-full cursor-pointer mr-2 border-2 h-12 w-12 flex
                        items-center shadow-md border-gray-300 justify-center"
                             v-for="(item,index) in questionList"
                             :class="{'myQuestionItm_finish': item.options}"
                             :key="index">
                            {{index+1}}
                        </div>
                    </div>
                </div>
                <div class="mainContainerRight ml-4">
                    <div class="flex justify-between shadow-sm MyBorder p-1">
                        <div>开始时间：{{startTime}}</div>
                        <div class="mr-2">剩余时间：
                            <span v-bind:class="{ 'text-red-600' : notMuchTime,'text-lg': notMuchTime}">
                            {{mins}}:{{secs}}
                            </span>
                        </div>
                    </div>

                    <div class="mt-4  ">
                        <div class="m-2 simple-answer-card" v-for="(item,index) in questionList">
                            <!-- 单选题 -->
                            <div v-if="item.type == 1">
                                <div class="text-black font-semibold text-lg">
                                    {{index+1}}.{{item.name}}
                                </div>
                                <div class="mt-1 mb -1">
                                    <el-tag size="mini">单选题</el-tag>
                                </div>
                                <div class="flex justify-content-between flex-wrap mt-4">
                                    <el-radio
                                            v-for="(ans,innerIndex) in item.answer"
                                            :key="innerIndex"
                                            :label="ans.option"
                                            v-model="item.options" border>
                                        {{ans.option}}. {{ans.value}}
                                    </el-radio>
                                </div>
                            </div>
                            <!-- 多选题 -->
                            <div v-if="item.type == 2">
                                <div class="text-black font-semibold text-lg">
                                    {{index+1}}.{{item.name}}
                                </div>
                                <div class="mt-1 mb -1">
                                    <el-tag size="mini">多选题</el-tag>
                                </div>
                                <div class="flex justify-content-between flex-wrap mt-4">
                                    <el-checkbox
                                            @change="checkboxChange(item,index)"
                                            v-for="(ans,innerIndex) in item.answer"
                                            :key="innerIndex"
                                            :label="ans.option"
                                            v-model="item.multipleChoiceAnswer" border>
                                        {{ans.option}}. {{ans.value}}
                                    </el-checkbox>
                                </div>
                            </div>
                            <!-- 判断题 -->
                            <div v-if="item.type == 3">
                                <div class="text-black font-semibold text-lg">
                                    {{index+1}}.{{item.name}}
                                </div>
                                <div class="mt-1 mb -1">
                                    <el-tag size="mini">判断题</el-tag>
                                </div>
                                <div class="flex justify-content-between flex-wrap mt-4">
                                    <el-radio v-model="item.options" label="对" border>对</el-radio>
                                    <el-radio v-model="item.options" label="错" border>错</el-radio>
                                </div>
                            </div>
                            <!-- 填空题 -->
                            <div v-if="item.type == 4">
                                <div class="text-black font-semibold text-lg">
                                    {{index+1}}.{{item.name}}
                                </div>
                                <div class="mt-1 mb -1">
                                    <el-tag size="mini">填空题</el-tag>
                                </div>
                                <div class="flex justify-content-between flex-wrap mt-4">
                                    <el-input
                                            placeholder="请输入答案"
                                            v-model="item.options"
                                            clearable>
                                    </el-input>
                                </div>
                            </div>

                        </div>

                    </div>
                </div>

            </div>


        </el-main>
    </el-container>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<!-- axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 引入element-ui组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    const answerQuestionsApp = new Vue({
        el: '#answerQuestionsApp',
        data() {
            return {
                // 试卷id
                paperId: '',
                startTime: '',
                // 试卷名称
                paperName: '苹果都是水果',
                // 剩余时间(单位：秒)
                remainingTime: 50,
                mins: 0,
                secs: 0,
                // 题目数量
                questionCount: 0,
                // 题目列表
                questionList: [],
                // 倒计时器
                countdownTimer: null,
                // 确认
                confirm: false,
                finished: true,
            }
        },
        methods: {
            formatDate: function (val) {
                const date = val;
                const seperator1 = "-";
                const seperator2 = ":";
                const year = date.getFullYear();
                let month = date.getMonth() + 1;
                let strDate = date.getDate();
                if (month >= 1 && month <= 9) {
                    month = "0" + month;
                }
                if (strDate >= 0 && strDate <= 9) {
                    strDate = "0" + strDate;
                }
                return year + seperator1 + month + seperator1 + strDate
                    + " " + date.getHours() + seperator2 + date.getMinutes()
                    + seperator2 + date.getSeconds();
            },
            goBack: function () {
                window.history.back();
            },
            countdown: function () {
                if (this.remainingTime > 0) {
                    this.remainingTime--;
                    this.mins = Math.floor(this.remainingTime / 60);
                    this.secs = this.remainingTime % 60;
                    if (this.secs < 10) {
                        this.secs = '0' + this.secs;
                    }
                } else {
                    // 倒计时结束
                    clearInterval(this.countdownTimer);
                    // 提交试卷
                    console.debug('提交试卷');
                }
            },
            checkboxChange: function (val) {
                console.debug(val);
                val.options = val.multipleChoiceAnswer.sort().join(',')
            },
            submitPaper: function () {
                const _this = this;
                // 组装请求参数
                const requestData = {
                    paperId: this.paperId,
                    userId: window.localStorage.getItem('userid'),
                    answers: [],
                };
                this.questionList.forEach(function (item) {
                    requestData.answers.push({
                        id: item.id,
                        options: item.options,
                    });
                });
                axios({
                    url: "/jspmk28g8/examination/submitExam",
                    method: 'post',
                    data: requestData,
                    headers: {
                        'Content-Type': 'application/json',
                        'token': window.localStorage.getItem('Token')
                    }
                }).then(res => {
                    console.debug(res)
                    const {code} = res.data;
                    if (code === 200) {
                        _this.$message({
                            message: '提交成功',
                            type: 'success'
                        });
                        // 延时跳转
                        setTimeout(function () {
                            _this.goBack()
                        }, 2000);
                    } else {
                        alert('提交失败');
                    }
                }).catch(err => {
                    console.error(err);
                })
            },
            carryOutAnAssignment: function () {
                const _this = this;
                console.debug('提交试卷');
                for (let i = 0; i < this.questionList.length; i++) {
                    if (!this.questionList[i].options) {
                        // 未完成
                        _this.finished = false;
                        break;
                    }
                }
                // 转换
                if (this.finished) {
                    _this.submitPaper()
                } else {
                    this.$confirm('未完成试卷, 是否继续提交?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        _this.submitPaper()
                    }).catch(() => {
                        return false;
                    });
                }
            }
        },
        created() {
            console.debug('created')
            this.startTime = this.formatDate(new Date());
        }
        ,
        mounted() {

            const _this = this;
            const paperId = window.localStorage.getItem("haveATestId");
            if (paperId) {
                this.paperId = parseInt(paperId)
            } else {
                // 未获取到试卷id，跳转到列表页
                this.$confirm('未获取到试卷信息，将返回列表', '提示', {
                    confirmButtonText: '确定',
                    showCancelButton: false,
                    showClose: false,
                    closeOnPressEscape: false,
                    closeOnClickModal: false,
                    type: 'warning'
                }).then(() => {
                    window.history.back();
                })
                return false;
            }
            // 请求考试信息
            axios({
                url: '/jspmk28g8/examination/getExamInfo',
                methods: 'get',
                params: {
                    paperId: _this.paperId
                },
                headers: {
                    'Content-Type': 'application/json',
                    'token': window.localStorage.getItem("Token")
                }
            }).then(res => {
                console.debug(res)
                const {code, data} = res.data;
                if (code === 200) {
                    _this.paperName = data.name;
                    _this.remainingTime = data.examduration * 60;
                    _this.questionCount = data.questionSize;
                    _this.questionList = [];
                    data.questions.forEach(it => {
                        let temp = {
                            id: it.id,
                            name: it.name,
                            type: it.type,
                            options: '',
                        }
                        if (it.type === 1) {
                            temp.answer = JSON.parse(it.answer);
                        } else if (it.type === 2) {
                            temp.answer = JSON.parse(it.answer);
                            temp.multipleChoiceAnswer = []
                        }
                        _this.questionList.push(temp)
                    })
                } else {
                    // 未获取到试卷id，跳转到列表页
                    this.$confirm('未获取到试卷信息，将返回列表', '提示', {
                        confirmButtonText: '确定',
                        showCancelButton: false,
                        showClose: false,
                        closeOnPressEscape: false,
                        closeOnClickModal: false,
                        type: 'warning'
                    }).then(() => {
                        window.history.back();
                    })
                    return false;
                }
            }).catch(err => {
                console.error(err)
            })
            this.countdownTimer = setInterval(() => {
                _this.countdown()
            }, 1000)
        }
        ,
        computed: {
            nowTime: function () {
                return this.formatDate(new Date())
            }
            ,
            notMuchTime: function () {
                return this.remainingTime <= 600
            }
        }
        ,
        beforeDestroy() {
            if (this.countdownTimer) {
                clearInterval(this.countdownTimer)
            }
        }
    })
</script>
</body>
</html>